import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  Button,
  Card,
  Checkbox,
  Col,
  Divider,
  Form,
  Input,
  message,
  Row,
  Space,
  Typography,
} from "antd";
import {
  AlipayOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
  LockOutlined,
  MobileOutlined,
  QqOutlined,
  SafetyCertificateOutlined,
  WechatOutlined,
} from "@ant-design/icons";
import { login } from "@/api/auth";
import useAuthStore from "@/store/authStore";
import logo from "@/assets/logo.svg";
import type { UserLoginDTO } from "@/types";

const { Title, Text } = Typography;

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [captchaLoading, setCaptchaLoading] = useState(false);
  const navigate = useNavigate();
  const setUser = useAuthStore((state) => state.setUser);
  const [form] = Form.useForm();

  // 使用 useWatch 监听手机号字段的变化
  const phoneValue = Form.useWatch("phone", form);

  // 手机号校验逻辑
  const validatePhone = (_: any, value: string) => {
    if (!value) {
      return Promise.reject("请输入手机号");
    }
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(value)) {
      return Promise.reject("请输入有效的手机号");
    }
    return Promise.resolve();
  };

  // 获取验证码
  const getCaptcha = async () => {
    try {
      await form.validateFields(["phone"]);
      setCaptchaLoading(true);
      setTimeout(() => {
        setCaptchaLoading(false);
        message.success("验证码已发送至您的手机");
      }, 1000);
    } catch (errorInfo) {
      console.log("Validation Failed:", errorInfo);
    }
  };

  const onFinish = async (values: UserLoginDTO) => {
    setLoading(true);
    try {
      const res = await login(values);
      if (res.success) {
        setUser(res.data);
        message.success("登录成功");
        navigate("/dashboard");
      } else {
        message.error(res.msg);
      }
    } catch (e) {
      console.log(e);
      message.error("登录失败，请检查网络或联系管理员");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-indigo-100 via-purple-100 to-pink-100 p-4 relative overflow-hidden">
      {/* 背景动画 */}
      <div className="absolute top-0 -left-4 w-72 h-72 bg-purple-300 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-blob"></div>
      <div className="absolute top-0 -right-4 w-72 h-72 bg-blue-300 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-blob animation-delay-2000"></div>
      <div className="absolute -bottom-8 left-20 w-72 h-72 bg-pink-300 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-blob animation-delay-4000"></div>

      <div className="w-full max-w-sm relative z-10">
        {/* Logo和标题区域 */}
        <div className="text-center mb-6">
          <div className="flex justify-center mb-4">
            <div className="relative group">
              <div className="absolute -inset-2 bg-gradient-to-r from-blue-400 to-purple-500 rounded-2xl blur opacity-70 group-hover:opacity-100 transition duration-300"></div>
              <div className="relative bg-white border-0 rounded-2xl w-16 h-16 flex items-center justify-center shadow-xl transform group-hover:scale-105 transition duration-300">
                <img className="h-10 w-10" src={logo} alt="Logo" />
              </div>
            </div>
          </div>
          <Title
            level={3}
            className="!text-2xl !font-bold !text-transparent bg-clip-text bg-gradient-to-r from-blue-600 to-purple-600 !mb-1 drop-shadow-md"
          >
            统一登录认证平台
          </Title>
          <Text className="!text-gray-600 !text-sm animate-fade-in delay-300">
            Secure & Reliable Authentication
          </Text>
        </div>

        {/* 登录表单卡片 */}
        <Card
          className="shadow-2xl border-0 rounded-3xl overflow-hidden bg-white/90 backdrop-blur-md transform transition-all duration-500 hover:scale-[1.01]"
          styles={{ body: { padding: "32px" } }}
        >
          <div className="mb-4 text-center">
            <Text className="!text-gray-800 !text-xl !font-semibold block animate-fade-in delay-500">
              欢迎回来
            </Text>
            <Text className="!text-gray-500 !block !mt-1 !text-sm animate-fade-in delay-600">
              请登录您的账户
            </Text>
          </div>

          <Form
            name="login"
            onFinish={onFinish}
            className="space-y-4"
            size="large"
            form={form} // 关键：已连接 form 实例
          >
            {/* 手机号和密码合并在同一行 */}
            <Form.Item name="phone" rules={[{ validator: validatePhone }]}>
              <Input
                prefix={<MobileOutlined className="text-indigo-500 mr-2" />}
                placeholder="手机号"
                className="!rounded-full !border-gray-300 !bg-gray-50 !h-11"
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: "请输入密码" }]}
            >
              <Input
                prefix={<LockOutlined className="text-indigo-500 mr-2" />}
                type={showPassword ? "text" : "password"}
                placeholder="密码"
                className="!rounded-full !border-gray-300 !bg-gray-50 !h-11"
                suffix={
                  <span
                    className="cursor-pointer pr-2"
                    onClick={() => setShowPassword(!showPassword)}
                  >
                    {showPassword ? (
                      <EyeOutlined className="text-gray-400 hover:text-indigo-500" />
                    ) : (
                      <EyeInvisibleOutlined className="text-gray-400 hover:text-indigo-500" />
                    )}
                  </span>
                }
              />
            </Form.Item>

            {/* 验证码部分简化为一行 */}
            <Row gutter={12}>
              <Col span={16}>
                <Form.Item
                  name="captcha"
                  rules={[{ required: true, message: "请输入验证码" }]}
                >
                  <Input
                    prefix={
                      <SafetyCertificateOutlined className="text-indigo-500 mr-2" />
                    }
                    placeholder="验证码"
                    className="!rounded-full !border-gray-300 !bg-gray-50 !h-11"
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Button
                  className="!w-full !rounded-full !bg-gradient-to-r !from-indigo-500 !to-purple-500 !border-none !text-white !font-semibold !h-11 shadow-md"
                  onClick={getCaptcha}
                  loading={captchaLoading}
                  // 使用 Form.useWatch 替代 form.getFieldValue，确保在正确时机执行
                  disabled={!phoneValue}
                >
                  {captchaLoading ? "发送中" : "获取"}
                </Button>
              </Col>
            </Row>

            {/* 记住我和忘记密码放在同一行，并调整间距 */}
            <div className="flex items-center justify-between">
              <Form.Item
                name="remember"
                valuePropName="checked"
                className="!mb-0"
              >
                <Checkbox className="!text-gray-600 [&_span]:!text-gray-500 text-sm">
                  记住我
                </Checkbox>
              </Form.Item>
              <a
                className="!text-indigo-600 hover:!text-indigo-800 !font-medium !transition-colors !text-sm"
                href="#"
              >
                忘记密码?
              </a>
            </div>

            <Form.Item className="!mb-0 !mt-2">
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                className="!w-full !h-12 !rounded-full !bg-gradient-to-r !from-indigo-600 !to-purple-600 !border-none !text-white !font-bold !shadow-lg hover:!shadow-xl !transition-all !duration-300 transform hover:-translate-y-1"
                size="large"
              >
                {loading ? "登录中..." : "安全登录"}
              </Button>
            </Form.Item>
          </Form>

          {/* 分割线和第三方登录 */}
          <Divider className="!my-6 !text-gray-400">
            <Text className="!text-gray-500 !text-sm">其他方式</Text>
          </Divider>

          <div className="grid grid-cols-3 gap-4">
            <Button className="!flex !items-center !justify-center !py-2 !border !border-gray-200 !rounded-full !bg-white !text-gray-600 !h-10">
              <WechatOutlined className="text-lg text-green-500" />
            </Button>
            <Button className="!flex !items-center !justify-center !py-2 !border !border-gray-200 !rounded-full !bg-white !text-gray-600 !h-10">
              <QqOutlined className="text-lg text-blue-500" />
            </Button>
            <Button className="!flex !items-center !justify-center !py-2 !border !border-gray-200 !rounded-full !bg-white !text-gray-600 !h-10">
              <AlipayOutlined className="text-lg text-blue-600" />
            </Button>
          </div>

          <div className="text-center mt-6">
            <Text className="!text-gray-600 !text-sm">还没有账户？</Text>
            <a
              className="!text-indigo-600 hover:!text-indigo-800 !font-semibold !ml-1 !transition-colors !text-sm"
              href="/register"
            >
              立即注册
            </a>
          </div>
        </Card>

        {/* 底部信息 */}
        <div className="text-center mt-6 animate-fade-in delay-700">
          <Space className="!flex !justify-center">
            <Text className="!text-gray-500 !text-xs">
              © CHIYU 统一登录认证平台
            </Text>
            <Text className="!text-gray-400 !text-xs">|</Text>
            <Text className="!text-gray-500 !text-xs">安全可靠</Text>
          </Space>
        </div>
      </div>
    </div>
  );
};

export default Login;
